<template>
	<view class="combo-card">
		<view class="card-header">
			<view class="header-left">
				<cl-tag type="warning" size="small">套餐</cl-tag>
				<text class="activity-name">{{ promotion.promName }}</text>
			</view>
			<view class="header-right">
				<text class="save-amount">立省¥{{ calculateSaveAmount() }}</text>
			</view>
		</view>

		<view class="combo-content">
			<!-- 套餐商品列表 -->
			<view class="combo-items">
				<view v-for="(item, index) in displayItems" :key="index" class="combo-item">
					<cl-image
						:src="'https://shop.sdamdyy.cn/' + (item.goodsInfo?.mainPic || '')"
						:alt="item.goodsInfo?.title"
						class="item-image"
						width="120rpx"
						height="120rpx"
						mode="aspectFill"
						:lazy-load="true"
						fallback="/static/empty/no.jpg"
					/>
					<view class="item-info">
						<text class="item-name">{{ item.goodsInfo?.title || "商品名称" }}</text>
						<text class="item-spec">{{ item.goodsInfo?.goodsSpec || "" }}</text>
						<text class="item-manufacturer">{{
							item.goodsInfo?.manufacturer || ""
						}}</text>
						<view class="item-price">
							<text class="price-label">单价:</text>
							<text class="price-value" v-if="userStore.token">{{
								formatUserPrice(
									item.taxprice,
									userStore,
									item.goodsInfo?.noDiscounts
								)
							}}</text>
							<text class="price-value" v-else>登录查看</text>
							<text class="price-quantity">x{{ Number(item.num || 1) }}</text>
						</view>
					</view>
					<view v-if="index < displayItems.length - 1" class="plus-icon">
						<cl-icon name="plus" size="24" color="#ffa500"></cl-icon>
					</view>
				</view>

				<!-- 更多商品提示 -->
				<view v-if="hasMore" class="more-items" @tap="showAllItems">
					<text class="more-text">还有{{ promotion.details.length - 3 }}个商品</text>
					<cl-icon name="arrow-down" size="20" color="#666"></cl-icon>
				</view>
			</view>

			<!-- 套餐价格汇总 -->
			<view class="price-summary">
				<view class="price-row">
					<text class="label">原价总计:</text>
					<text class="original-total">¥{{ calculateOriginalTotal() }}</text>
				</view>
				<view class="price-row">
					<text class="label">套餐价格:</text>
					<text class="combo-price">¥{{ calculateComboPrice() }}</text>
				</view>
				<view class="save-badge">
					<cl-icon name="tag" size="16" color="#ff6b6b"></cl-icon>
					<text class="save-text">节省{{ calculateDiscountPercent() }}%</text>
				</view>
			</view>

			<!-- 购买操作 -->
			<view class="action-area">
				<view class="quantity-selector">
					<text class="quantity-label">购买套数：</text>
					<cl-input-number v-model="quantity" :min="1" :max="99" :size="30" />
				</view>
				<cl-button type="warning" size="medium" round @tap="handleBuy">
					立即购买
				</cl-button>
			</view>
		</view>

		<!-- 活动信息 -->
		<view class="footer-info">
			<view class="info-item">
				<cl-icon name="time" size="14" color="#999"></cl-icon>
				<text class="info-text">{{ formatActivityTime() }}</text>
			</view>
			<view class="info-item">
				<cl-icon name="info" size="14" color="#999"></cl-icon>
				<text class="info-text">{{ promotion.statusText }}</text>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { useCool } from "/@/cool";
import { useStore } from "/@/cool/store";
import { formatUserPrice, calculateUserPrice } from "/@/utils/price";
import dayjs from "dayjs";

const { service, router } = useCool();
const { user: userStore } = useStore();

const props = defineProps<{
	promotion: any;
}>();

const emit = defineEmits(["join"]);

const quantity = ref(1);
const showAll = ref(false);

// 显示的商品列表
const displayItems = computed(() => {
	if (!props.promotion.details) return [];
	if (showAll.value) return props.promotion.details;
	return props.promotion.details.slice(0, 3);
});

// 是否有更多商品
const hasMore = computed(() => {
	return props.promotion.details && props.promotion.details.length > 3 && !showAll.value;
});

// 计算原价总计
function calculateOriginalTotal(): string {
	if (!props.promotion.details) return "0.00";
	const total = props.promotion.details.reduce((sum: number, item: any) => {
		const price = calculateUserPrice(
			item.goodsInfo?.price || 0,
			userStore.info,
			item.goodsInfo?.noDiscounts
		);
		const num = Number(item.num || 1);
		return sum + price * num;
	}, 0);
	return (total * quantity.value).toFixed(2);
}

// 计算套餐价格
function calculateComboPrice(): string {
	if (!props.promotion.details) return "0.00";
	const total = props.promotion.details.reduce((sum: number, item: any) => {
		const price = calculateUserPrice(
			item.taxprice || 0,
			userStore.info,
			item.goodsInfo?.noDiscounts
		);
		const num = Number(item.num || 1);
		return sum + price * num;
	}, 0);
	return (total * quantity.value).toFixed(2);
}

// 计算节省金额
function calculateSaveAmount(): string {
	const original = Number(calculateOriginalTotal());
	const combo = Number(calculateComboPrice());
	return (original - combo).toFixed(2);
}

// 计算折扣百分比
function calculateDiscountPercent(): string {
	const original = Number(calculateOriginalTotal());
	const save = Number(calculateSaveAmount());
	if (original === 0) return "0";
	return ((save / original) * 100).toFixed(0);
}

// 显示所有商品
function showAllItems() {
	showAll.value = true;
}

// 处理购买
async function handleBuy() {
	try {
		uni.showLoading({ title: "下单中..." });

		// 调用套餐下单接口
		await service.goods.promo.createComboOrder({
			billNo: props.promotion.billNo,
			quantity: quantity.value,
		});

		uni.hideLoading();
		uni.showToast({
			title: "下单成功",
			icon: "success",
		});

		// 跳转到订单页面
		setTimeout(() => {
			router.push("/pages/order/list");
		}, 1500);
	} catch (error: any) {
		uni.hideLoading();
		uni.showToast({
			title: error.message || "下单失败",
			icon: "none",
		});
	}
}

// 格式化活动时间
function formatActivityTime(): string {
	const start = dayjs(props.promotion.startTime);
	const end = dayjs(props.promotion.endTime);
	return `${start.format("MM/DD HH:mm")} - ${end.format("MM/DD HH:mm")}`;
}
</script>

<style lang="scss" scoped>
.combo-card {
	background: #fff;
	border-radius: 16rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx;
		background: linear-gradient(135deg, #ffa500 0%, #ff8c00 100%);
		color: #fff;

		.header-left {
			display: flex;
			align-items: center;
			gap: 12rpx;

			.activity-name {
				font-size: 32rpx;
				font-weight: bold;
			}
		}

		.save-amount {
			font-size: 28rpx;
			font-weight: 500;
		}
	}

	.combo-content {
		padding: 24rpx;

		.combo-items {
			margin-bottom: 24rpx;

			.combo-item {
				display: flex;
				align-items: center;
				gap: 16rpx;
				padding: 16rpx;
				background: #f8f8f8;
				border-radius: 12rpx;
				margin-bottom: 16rpx;

				.item-image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 8rpx;
					flex-shrink: 0;
				}

				.item-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					gap: 8rpx;

					.item-name {
						font-size: 28rpx;
						font-weight: 500;
						color: #333;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
					}

					.item-spec {
						font-size: 24rpx;
						color: #666;
					}

					.item-manufacturer {
						font-size: 22rpx;
						color: #999;
					}

					.item-price {
						display: flex;
						align-items: center;
						gap: 8rpx;
						font-size: 26rpx;

						.price-label {
							color: #666;
						}

						.price-value {
							color: #ff6b6b;
							font-weight: 500;
						}

						.price-quantity {
							color: #999;
						}
					}
				}

				.plus-icon {
					flex-shrink: 0;
				}
			}

			.more-items {
				display: flex;
				justify-content: center;
				align-items: center;
				gap: 8rpx;
				padding: 16rpx;
				background: #f0f0f0;
				border-radius: 8rpx;

				.more-text {
					font-size: 26rpx;
					color: #666;
				}
			}
		}

		.price-summary {
			background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%);
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 24rpx;
			position: relative;

			.price-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 12rpx;

				.label {
					font-size: 28rpx;
					color: #666;
				}

				.original-total {
					font-size: 28rpx;
					color: #999;
					text-decoration: line-through;
				}

				.combo-price {
					font-size: 36rpx;
					font-weight: bold;
					color: #ff6b6b;
				}
			}

			.save-badge {
				position: absolute;
				top: 20rpx;
				right: 20rpx;
				display: flex;
				align-items: center;
				gap: 6rpx;
				background: #fff;
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

				.save-text {
					font-size: 24rpx;
					color: #ff6b6b;
					font-weight: 500;
				}
			}
		}

		.action-area {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.quantity-selector {
				display: flex;
				align-items: center;
				gap: 12rpx;

				.quantity-label {
					font-size: 28rpx;
					color: #666;
				}
			}
		}
	}

	.footer-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 24rpx;
		background: #f8f8f8;

		.info-item {
			display: flex;
			align-items: center;
			gap: 8rpx;

			.info-text {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
}
</style>
